import { Component, OnInit, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import { environment } from '../../../../environments/environment';
import { _HttpClient } from '@delon/theme';
import './font/iconfont.js';
import { ArticleManegeService } from '../articleManege/articleManege.service';
import { DatePipe } from '@angular/common';
import { IndexKmnDetailComponent } from './detail/index.component.detail';
import { LocalStorage } from '@core/local.storage';
import { NzMessageService } from 'ng-zorro-antd';
import { MenuTreeService } from '@core/menuTree.service';
import { forkJoin } from 'rxjs';

@Component({
    selector: 'app-index-kmn',
    templateUrl: './index.component.html',
    styleUrls: ['./index.less']
})

export class IndexKmnComponent implements OnInit {
    @ViewChild('indexDetail', { static: true }) indexDetail: IndexKmnDetailComponent;
    detailPage = false;
    mainPage = true;
    tongzhiList: any[] = [];
    xuexiList: any[] = [];
    quntuanList: any[] = [];
    detailId = 0;
    catagoryId: any;
    searchKey = '';
    leaderInfos: any[] = [];
    dateInfo: any = {};
    selectedMenu = 'index';
    screenType = '';
    screen: any = {};
    classes: any = {};
    userInfo = JSON.parse(this.ls.get('loginInfo'));

    links = {
        aqsc: environment.outLink + '/#/control', // 安全生产
        bzhtx: environment.standard + '/#/index', // 标准化体系
        aqfxglxt: 'http://10.207.193.10:7001/ktaj_srmis/', // 安全风险管理系统
        jbxx_jiwei: 'petitionView/edit', // 在线举报
        jbxx: environment.outLink + '/#/onlineComplaint', // 在线举报
        kmtljbgxxw: 'http://www.kunm.cr/site/', // 昆明铁路局办公信息网
        ddsgxt: 'http://construct.tdms52.kunm.cr:7001/ljdd/sgd/', // 施工调度系统TDMS5
        tlwzglxxxt: 'http://wzxt.kunm.cr/pages/login.aspx', // 铁路物资管理信息系统
        ktzjxxwlpt: 'http://10.206.22.68/cms/', // 昆铁职教信息网络平台
        // kmjjtdwb: 'http://10.207.193.12/dwc/', // 昆明局集团电务部
        kmjjtjsgzxt: 'http://10.206.4.83:7002/rule2/', // 昆明局集团技术规章系统
        kmjkjxmglpt: 'http://ktkj.kunm.cr/mgr/', // 昆明局科技项目管理平台
        xtgl: environment.outLink + '/#/xtbg/zdrwgzqd/duanquery', // 重点任务工作清单
    };
    breadList: any[] = [];
    loadTableByKey: any;

    constructor(
        public mt: MenuTreeService,
        public ls: LocalStorage,
        private router: Router,
        private http: _HttpClient,
        private articleManegeService: ArticleManegeService,
        private datePipe: DatePipe,
        private message: NzMessageService
    ) { }

    ngOnInit() {
        this.initScreen();
        this.getArticles();
        this.initLeader();
        this.initDate();
    }

    initLeader() {
        const param = {};
        this.getLeader(param).subscribe(res => {
            if (res && res.response && res.response.data) {
                this.leaderInfos = res.response.data;
            }
        });
    }

    initDate() {
        this.dateInfo.date = this.datePipe.transform(new Date(), 'yyyy-MM-dd')
        this.dateInfo.day = this.datePipe.transform(new Date(), 'EEEE');
    }

    checkLoginState() {
        if (this.userInfo) {
            return true;
        }
        this.message.warning('请登录以查看内容');
        return false;
    }

    getLeader(param) {
        const dataurl = environment.apiBase + '/csmis/duty/getDutyLeaderInfo.jwt';
        return this.http.get(dataurl, param);
    }

    goto(param) {
        if (!this.checkLoginState()) {
            return;
        }
        const page = param.page;
        this.searchKey = '';
        switch (page) {
            case 'main':
                this.detailPage = false;
                this.mainPage = true;
                this.selectedMenu = 'index';
                break;
            case 'detail_table':
                this.mainPage = false;
                this.detailPage = true;
                if (param.searchKey) {
                    this.searchKey = param.searchKey;
                } else {
                    if (param.catagoryId) {
                        this.detailId = undefined;
                        this.catagoryId = param.catagoryId;
                    }
                }
                break;
            case 'detail_article':
                if (param.id) {
                    this.detailId = param.id;
                }
                if (param.catagoryId) {
                    this.catagoryId = param.catagoryId;
                }
                this.mainPage = false;
                this.detailPage = true;
                break;
            default:
                break;
        }
    }

    login() {
        this.router.navigate(['passport/login']);
    }

    getArticles() {
        const updateApi = [
            this.http.get(environment.apiBase + '/csmis/news/index.jwt?category=tongzhilan'),
            this.http.get(environment.apiBase + '/csmis/news/index.jwt?category=xuexijiaoliu'),
            this.http.get(environment.apiBase + '/csmis/news/index.jwt?category=quntuangongzuo')
        ];
        forkJoin(updateApi).subscribe((results: any) => {
            this.tongzhiList = results[0];
            this.xuexiList = results[1];
            this.quntuanList = results[2];        
        });
    }

    beforeShow(data) {
        data.forEach(row => {
            if (row.operTime) {
                row._operDate = this.datePipe.transform(row.operTime, 'yyyy-MM-dd')
            }
        });
    }

    // 如果关键词与上次相同，则直接切换页面不进行查询
    // 如果关键词发生改变，则查询由组件的onchange方法自己触发
    // @param v

    searchAll(v) {
        if (!this.checkLoginState()) {
            return;
        }
        this.searchKey = v;
        this.mainPage = false;
        this.detailPage = true;
        if (this.indexDetail) {
            this.indexDetail.loadTableByKey(v);
        }
    }

    breadChange(breadArr) {
        this.breadList = [];
        breadArr.forEach(v => {
            const breadItem: any = {};
            breadItem.text = v.text;
            switch (v.type) {
                case 'key': // 关键词
                    breadItem.click = (_v) => {
                        this.searchAll(_v.text);
                    };
                    break;
                case 'category': // 文章类型
                    breadItem.value = v.value;
                    breadItem.click = (_v) => {
                        this.goto({ page: 'detail_table', catagoryId: _v.value });
                    };
                    break;

                default:
                    break;
            }
            this.breadList.push(breadItem);
        });
    }

    menuClick(type) {
        if (!this.checkLoginState()) {
            return;
        }
        this.selectedMenu = type;
        switch (type) {
            case 'index':
                this.router.navigate(['indexkmn']);
                break;
            case 'aqsc': // 安全生产
            case 'bzhtx': // 标准化体系
            case 'xtgl': // 协同管理
                this.windowOpen(this.links[type]);
                break;
            case 'tzgg': // 通知公告
                this.goto({ page: 'detail_table', catagoryId: 'tongzhilan' });
                break;
            case 'xxyd': // 学习园地
                this.goto({ page: 'detail_table', catagoryId: 'xuexijiaoliu' });
                break;
            case 'qtgz': // 群团工作
                this.goto({ page: 'detail_table', catagoryId: 'quntuangongzuo' });
                break;
            case 'aqfxglxt': // 群团工作
            case 'kmtljbgxxw': // 群团工作
            case 'ddsgxt': // 群团工作
            case 'tlwzglxxxt': // 群团工作
            case 'ktzjxxwlpt': // 群团工作
            // case 'kmjjtdwb': // 群团工作
            case 'kmjjtjsgzxt': // 群团工作
            case 'kmjkjxmglpt': // 群团工作
                this.windowOpen(this.links[type]);
                break;
        }
    }
    // 在线举报
    menuClickJbxx() {
        if (this.userInfo.VC_NUMBER) {
            this.http.get(environment.devscore + '/letter/checkUserAuth?userId=' + this.userInfo.VC_NUMBER).subscribe(res => {
                if (!res.code) {
                    if (res.data[0]) {
                        this.router.navigate([this.links.jbxx_jiwei]);
                    } else {
                        this.windowOpen(this.links.jbxx);
                    }
                }
            });
        } else {
            this.windowOpen(this.links.jbxx);
        }
    }
    windowOpen(url) {
        window.open(url, '_blank');
        return false;
    }

    judgeScreen() {
        const screenWidth = screen.width;
        if (screenWidth <= 1280) {
            this.screenType = '3';
        } else if (screenWidth <= 1600) {
            this.screenType = '2';
        } else {
            this.screenType = '1';
        }
    }
    initScreen() {
        const spanMap = {
            '1': '4',
            '2': '3',
            '3': '1',
        };
        this.judgeScreen();
        this.initClasses();
        this.screen.emptyColSpan = spanMap[this.screenType];
        this.screen.mainColSpan = (24 - 2 * spanMap[this.screenType]) + '' || '16';
    }
    initClasses() {
        this.classes = {
            headCol: `headCol${this.screenType}`,
            titleInfoBar: `titleInfoBar${this.screenType}`,
            leftMenu: `leftMenu${this.screenType}`,
            articalHead: `articalHead${this.screenType}`,
            cardText: `cardText${this.screenType}`,
            cardIcon: `cardIcon${this.screenType}`,
            footer: `footer${this.screenType}`,
            articalList: `articalList${this.screenType}`,
        };
    }
    getSpan(num, sum, _method) {
        const method = _method || 'floor';
        return Math[method](num / sum * this.screen.mainColSpan);
    }
}
